﻿#include "EasySelectClient.h"

EasySelectClient::~EasySelectClient()
{
	Close();
}

// 发送数据
// 处理网络消息
bool EasySelectClient::OnRun(int microseconds)
{
	if (!IsRun())
	{
		return false;
	}
	SOCKET sock = _pClient->sockfd();
	FD_ZERO(&_fRead);
	FD_SET(sock, &_fRead);
	FD_ZERO(&_fWrite);
	struct timeval ti = { 0, microseconds };
	int ret = 0;
	// 如果客户端缓冲区里有数据可以发送给服务端，就添加可写检测
	if (_pClient->needWrite())
	{
		FD_SET(sock, &_fWrite);
		ret = select(sock + 1, &_fRead, &_fWrite, nullptr, &ti);
	}
	else
	{
		ret = select(sock + 1, &_fRead, nullptr, nullptr, &ti);
	}

	if (ret < 0)
	{
		CELLLog_Error("<sock=%d> OnRun select error exit on line %d", (int)sock, __LINE__);
		Close();
		return false;
	}

	if (FD_ISSET(sock, &_fRead))
	{
		if (RecvData() == SOCKET_ERROR)
		{
			CELLLog_Error("<sock=%d> RecvData select error exit on line %d", (int)sock, __LINE__);
			Close();
			return false;
		}
	}

	if (FD_ISSET(sock, &_fWrite))
	{
		if (_pClient->SendDataReal() == SOCKET_ERROR)
		{
			CELLLog_Error("<sock=%d> SendDataReal select error exit on line %d", (int)sock, __LINE__);
			Close();
			return false;
		}
	}
	return true;
}
